2023/12/231647字符
正则
命名捕获 ?
let str = '2019-03-21';
let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
let {year, month, day} = str.match(reg).groups; // match() 检索指定的值或找到一个或多个正则表达式的匹配
console.log(year, month, day);
反向引用 \k
let reg = /^(?<strive>welcome)-\k<strive>$/;
let str = 'welcome-welcome';
console.log(reg.test(str)); //--> true test() 检测一个字符串是否匹配某个模式
let reg = /^(?<strive>welcome)-\k<strive>-\1$/;
let str = 'welcome-welcome-welcome';
console.log(reg.test(str)); //--> true
替换 $
let str = '2019-03-21';
let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
str = str.replace(reg, '$<month>/$<day>/$<year>'); // replace() 用一些字符替换另一些字符
console.log(str);
dotAll模式 s
let reg = /^\w+.\w+$/s; // 使 . 匹配之前匹配不了的
let str = 'abc\nbcd';
console.log(reg.test(str)); //--> true
按码点判断字符串长度 u
let str = 'abc奈斯';
let reg = /./u;
console.log(reg.test(str)); //--> true
具名引用
const RE_DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const matchObj = RE_DATE.exec("1999-12-31");
const year = matchObj.groups.year;
const month = matchObj.groups.month;
const day = matchObj.groups.day;
console.log(year, month, day); //--> 1999 12 31
后行断言
/(?<=\$)\d+/.exec('Benjamin Franklin is on the $100 bill'); //--> ["100"]
/(?<!\$)\d+/.exec('it’s is worth about €90'); //--> ["90"]